package com.thesis.client;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SeekBar;
import android.widget.Spinner;

import com.thesis.client.ListTypeView.SizeCallback;
import com.thesis.conectify.Connectify;
import com.thesis.object.Bill;
import com.thesis.object.BillDescription;
import com.thesis.object.Dish;
import com.thesis.object.DishDetailAddBill;
import com.thesis.object.ListDishType;
import com.thesis.object.ListDishes;
import com.thesis.object.ListServeTableDetail;
import com.thesis.object.ServeTableDetail;
import com.thesis.object.Session;
import com.thesis.utils.Defines;
import com.thesis.utils.Utils;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class MenuActivity extends Activity {
	ListTypeView scrollView;

	View menu_foodtype;
	View menu_food;
	Button btnSlide;
	ImageView btn_confirm;
	SearchView sv_food;
	Spinner sp_table;
	static boolean menuOut = false;
	boolean isScan = false;
	Handler handler = new Handler();
	int btnWidth;
	FoodsAdapter foodAdapter;
	FoodTypeAdapter foodTypeAdapter;
	ProgressDialog mProgress;
	boolean loadingFinished = true;
	boolean redirect = false;
	AlertDialog.Builder alert;
	ListView list_foods;
	ListDishType listType;
	Bill bill;
	ListDishes listDishes;
	ArrayList<ServeTableDetail> list_fi = ListServeTableDetail.getInstance().getListServeTableDetail();
	ArrayList<Dish> arr_listfood;
	ArrayList<DishDetailAddBill> arr_food_addbill = new ArrayList<DishDetailAddBill>();
	ArrayList<DishDetailAddBill> arr_food_modifybill = new ArrayList<DishDetailAddBill>();
	ArrayList<DishDetailAddBill> arr_food_deletebill = new ArrayList<DishDetailAddBill>();
	ArrayList<DishDetailAddBill> arr_food_search = new ArrayList<DishDetailAddBill>();
	ArrayList<String> arr_table = new ArrayList<String>();
	ListServeTableDetail arr_all ;
	int bill_id;
	String[] receive;


	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (Build.VERSION.SDK_INT >= 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();

			StrictMode.setThreadPolicy(policy);
		}

		LayoutInflater inflater = LayoutInflater.from(this);
		scrollView = (ListTypeView) inflater.inflate(
				R.layout.screen_scroll_with_list_menu, null);
		setContentView(scrollView);
		 receive = getIntent().getStringArrayExtra(
				Defines.ID_USER_TABLE_MENU);
		 
		
	
		
		menu_foodtype = inflater.inflate(R.layout.foodtype_menu, null);
		menu_food = inflater.inflate(R.layout.activity_menu, null);
		ViewGroup tabBar = (ViewGroup) menu_food.findViewById(R.id.tabBar);
		list_foods = (ListView) menu_food.findViewById(R.id.menu_list_food);
		btn_confirm = (ImageView) menu_food.findViewById(R.id.m_btn_accept);
		sv_food = (SearchView) menu_food.findViewById(R.id.m_sv_food);
		sp_table = (Spinner) menu_food.findViewById(R.id.m_spinner_table);
		if(Session.getInstance().getRole() != 0){
			btn_confirm.setVisibility(View.GONE);
			sp_table.setVisibility(View.INVISIBLE);
		}
		
		new getAllBillandTableAvai().execute();

		
		
//---------------------------Searchview----------------------------------------------
		
		sv_food.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				doFilter(query);
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				doFilter(newText);
				return false;
			}
			
			public void doFilter(String str) {
				arr_listfood.clear();
				for (Dish item : ListDishes.getInstance().getListDishes()){
					if (item.getKeySearch().toUpperCase().contains(str.toString().toUpperCase())){
						
						arr_listfood.add(item);						
					}
					 list_foods.setAdapter(new FoodsAdapter(MenuActivity.this, arr_listfood, arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill));	
				}
							
			
			}
			
		}) ;
//-------------------------------Spinner-------------------------------------------------
		sp_table.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				// TODO Auto-generated method stub
				bill_id =  Utils.sharedInstance().getBillId(arr_table.get(pos));
				Log.d("bill_id",""+bill_id);
				bill = Utils.sharedInstance().getBill(arr_table.get(pos));
				arr_food_addbill = new ArrayList<DishDetailAddBill>();
				arr_food_modifybill = new ArrayList<DishDetailAddBill>();
				arr_food_deletebill = new ArrayList<DishDetailAddBill>();
				
				foodAdapter = new FoodsAdapter(MenuActivity.this, arr_listfood ,arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill);
				list_foods.setAdapter(foodAdapter);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
//----------------------------Button confirm----------------------------------------		
		btn_confirm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				new AlertDialog.Builder(MenuActivity.this)
				.setTitle("Xác nhận các món đã chọn")
				.setMessage("Bạn có chắc chắn?")
				.setPositiveButton(
						"Xác nhận",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog,
									int which) {
								Log.d("con ga` ","a"+arr_food_addbill.size()+"-m"+arr_food_modifybill.size()+"-d"+arr_food_deletebill.size());
								
								if (arr_food_addbill.size() > 0){
									
									new AddDishToBill().execute();
								}
								if (arr_food_modifybill.size() > 0){
									
								 new ModifyDishToBill().execute();
								
								}
								
								if (arr_food_deletebill.size() > 0){
									
									new DeleteDishToBill().execute();
									
								} 
								
								ListServeTableDetail.getInstance().clear();
								new updateListServeDetail().execute();
								
								
							}
						})
				.setNegativeButton(
						"Hủy",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog,
									int which) {
								// do nothing
							}
						}).show();
			}
		});
		
		
		
		
//--------------------------------------------------------------------------------		
		ListView listView = (ListView) menu_foodtype.findViewById(R.id.list_foodtype);
		

		// address = Config.createAddress();
		foodTypeAdapter = new FoodTypeAdapter(MenuActivity.this,
				R.layout.item_foodtype, listType);
		
		listView.setAdapter(foodTypeAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Context context = view.getContext();

				menuOut = true;
				scrollView(scrollView, menu_foodtype);
				menuOut = false;
				
				arr_listfood = Utils.sharedInstance().getListFoodByTypeId( ListDishes.getInstance(), ListDishType.getInstance().getListDishTypes().get(position).getId());
				
			   list_foods.setAdapter(new FoodsAdapter(MenuActivity.this, arr_listfood, arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill));
				Log.d("arr_listfood",""+arr_listfood.size());
			}
		});

		btnSlide = (Button) tabBar.findViewById(R.id.BtnSlide);

		btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView,
				menu_foodtype));

		final View[] children = new View[] { menu_foodtype, menu_food };

		// Scroll to app (view[1]) when layout finished.
		int scrollToViewIdx = 1;

		scrollView.initViews(children, scrollToViewIdx,
				new SizeCallbackForMenu(btnSlide));
	}

	/**
	 * Helper for examples with a HSV that should be scrolled by a menu View's
	 * width.
	 */
	private void scrollView(ListTypeView scrollView, View menu) {
		Context context = menu.getContext();

		int menuWidth = menu.getMeasuredWidth();

		// Ensure menu is visible
		menu.setVisibility(View.VISIBLE);

		if (!menuOut) {
			// Scroll to 0 to reveal menu
			Log.d("===slide==", "Scroll to right");
			int left = 0;
			scrollView.smoothScrollTo(left, 0);
		} else {
			// Scroll to menuWidth so menu isn't on screen.
			Log.d("===slide==", "Scroll to left");
			int left = menuWidth;
			scrollView.smoothScrollTo(left, 0);

		}
		menuOut = false;
	}

	// -----------------------------------------
	public void getTable() {

		for (int i = 0; i < ListServeTableDetail.getInstance()
				.getListServeTableDetail().size(); i++) {
			if (ListServeTableDetail.getInstance()
					.getListServeTableDetail().get(i).getTable().getTableName().equals(receive[1])){
				arr_table.add(0, ListServeTableDetail.getInstance()
						.getListServeTableDetail().get(i).getTable().getTableName());
			}
			else {
				arr_table.add(ListServeTableDetail.getInstance()
						.getListServeTableDetail().get(i).getTable().getTableName());
			} 
			
		}
	}
	public int getPositionTable (String re){
		for (int i =0; i<= arr_table.size();i++){
			if (re.equals(arr_table.get(i))) return i;
		}
		return 0;
	}
	// -----------------------------------------------------------------------
	static class ClickListenerForScrolling implements OnClickListener {
		ListTypeView scrollView;
		View menu;

		/**
		 * Menu must NOT be out/shown to start with.
		 */
		// boolean menuOut = false;

		public ClickListenerForScrolling(ListTypeView scrollView, View menu) {
			super();
			this.scrollView = scrollView;
			this.menu = menu;
		}

		@Override
		public void onClick(View v) {
			Context context = menu.getContext();

			int menuWidth = menu.getMeasuredWidth();

			// Ensure menu is visible
			menu.setVisibility(View.VISIBLE);

			if (!menuOut) {
				// Scroll to 0 to reveal menu
				Log.d("===slide==", "Scroll to right");
				Log.d("===clicked==", "clicked");
				int left = 20;
				scrollView.smoothScrollTo(left, 0);
			} else {
				// Scroll to menuWidth so menu isn't on screen.
				Log.d("===slide==", "Scroll to left");
				Log.d("===clicked==", "clicked");
				int left = menuWidth;
				scrollView.smoothScrollTo(left, 0);
			}
			menuOut = !menuOut;
		}
	}

	/**
	 * Helper that remembers the width of the 'slide' button, so that the
	 * 'slide' button remains in view, even when the menu is showing.
	 */
	static class SizeCallbackForMenu implements SizeCallback {
		int btnWidth;
		View btnSlide;

		public SizeCallbackForMenu(View btnSlide) {
			super();
			this.btnSlide = btnSlide;
		}

		@Override
		public void onGlobalLayout() {
			btnWidth = btnSlide.getMeasuredWidth();
			System.out.println("btnWidth=" + btnWidth);
		}

		@Override
		public void getViewSize(int idx, int w, int h, int[] dims) {
			dims[0] = w;
			dims[1] = h;
			final int menuIdx = 0;
			if (idx == menuIdx) {
				dims[0] = w - btnWidth;
			}
		}
	}

	@Override
	protected void onResume() {

		super.onResume();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		ListServeTableDetail.getInstance().clear();
		super.onDestroy();
	}
	public void addDishForTable(int bill_id){
		arr_food_addbill = new ArrayList<DishDetailAddBill>();
		for (int i = 0 ; i < list_fi.size();i++){
			if (list_fi.get(i).getBill().getId() == bill_id){
				ArrayList<BillDescription> cur = list_fi.get(i).getBill().getListDishDes().getListBill();
				for (int j = 0 ; j < cur.size(); j++){
					arr_food_addbill.add(new DishDetailAddBill(cur.get(j).getFoodId(),cur.get(j).getNumber(),cur.get(j).getFoodNote()));
				}
			}
		}
	}
	
	class getAllBillandTableAvai extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			Connectify connect = new Connectify(MenuActivity.this);
			if(Session.getInstance().getRole() == 0){
				connect.getListBillAvailableByUser(Integer.parseInt(receive[0]));
			}
			 

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			getTable();
			if(Session.getInstance().getRole() == 0){
				bill_id = Utils.sharedInstance().getBillId(arr_table.get(0));
				//Log.d("bill_id",""+bill_id);
				 bill = Utils.sharedInstance().getBill(arr_table.get(0));
				 Log.d("bill size", "" + bill.getId() + "-" + bill.getListDishDes().getListBill().size());
				
				arr_listfood = Utils.sharedInstance().getListFoodByTypeId( ListDishes.getInstance(), 0);
				
				foodAdapter = new FoodsAdapter(MenuActivity.this, arr_listfood ,arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill);
				
				list_foods.setAdapter(foodAdapter);
				
				// TODO Auto-generated method stub
				
				ArrayAdapter<String> spinner_adapter= new ArrayAdapter<String>(MenuActivity.this, android.R.layout.simple_spinner_item, arr_table);
				spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				
				sp_table.setAdapter(spinner_adapter);
			}
			else{
				
				arr_listfood = Utils.sharedInstance().getListFoodByTypeId( ListDishes.getInstance(), 0);
				
				foodAdapter = new FoodsAdapter(MenuActivity.this, arr_listfood ,arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill);
				
				list_foods.setAdapter(foodAdapter);
			}
				
			
			
			
			super.onPostExecute(result);
		}
	}
	
	class AddDishToBill extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Connectify connect = new Connectify(MenuActivity.this);
			
			connect.addDishToBill(bill_id, arr_food_addbill);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			arr_food_addbill = new ArrayList<DishDetailAddBill>();
			
			super.onPostExecute(result);
		}
		
	}
	class ModifyDishToBill extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			Connectify connect = new Connectify(MenuActivity.this);
			connect.modifyDishInBill(bill_id, arr_food_modifybill);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			arr_food_modifybill = new ArrayList<DishDetailAddBill>();
			
			super.onPostExecute(result);
		}
		
	}
	class DeleteDishToBill extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			Connectify connect = new Connectify(MenuActivity.this);
			connect.deleteDishInBill(bill_id, arr_food_deletebill);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			arr_food_deletebill = new ArrayList<DishDetailAddBill>();
			super.onPostExecute(result);
		}
	}
	
	class updateListServeDetail extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... arg0) {
			Connectify connect = new Connectify(MenuActivity.this);			
			connect.getListBillAvailableByUser(Integer.parseInt(receive[0]));
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			arr_listfood = Utils.sharedInstance().getListFoodByTypeId( ListDishes.getInstance(), 0);	
			for (int i = 0 ; i < ListServeTableDetail.getInstance().getListServeTableDetail().size();i++){
				if (ListServeTableDetail.getInstance().getListServeTableDetail().get(i).getBill().getId() == bill_id){
					bill = ListServeTableDetail.getInstance().getListServeTableDetail().get(i).getBill();
					break;
				}
			}
			foodAdapter = new FoodsAdapter(MenuActivity.this, arr_listfood ,arr_food_addbill,arr_food_modifybill,arr_food_deletebill,bill);			
			list_foods.setAdapter(foodAdapter);
			super.onPostExecute(result);
		}
	}
}
